<template>
  <div class="dialog-container">
    <el-dialog
      :close-on-click-modal="true"
      custom-class="add-template-dialog"
      :title="'编辑运维单详情'"
      :visible="dialogVisible"
      width="65%"
      @open="initData"
      @close="closeDialog"
    >
      <el-form
        ref="form"
        :model="dataForm"
        class="dialog-form"
        label-width="110px"
        size="mini"
      >
        <el-card>
          <div slot="header" class="clearfix">
            <el-row style="font-weight: bold;font-size: 14px;">
              <el-col :span="8">排口名称：{{ dataForm.outletName ? dataForm.outletName : '' }}</el-col>
              <el-col :span="8">排口类型：{{ dataForm.outletTypeName }}</el-col>
              <el-col :span="8">设备类型：{{ dataForm.equipmentTypeName }}</el-col>
            </el-row>
          </div>
          <div class="tabs-panel">
            <el-tabs
              v-model="editableTabsValue"
              type="card"
              editable
              @edit="handleTabsEdit"
            >
              <el-tab-pane
                v-for="(item,index) in dataForm.list"
                :key="index + 'tab'"
                :label="item.formTempIdName || '请选择'"
                :name="(index+1)+''"
              >
                <el-form-item label="类型" prop="formTempId">
                  <el-select
                    :ref="'tab_select'+index"
                    v-model="item.formTempId"
                    class="w-150"
                    filterable
                    remote
                    clearable
                    reserve-keyword
                    placeholder="请输入"
                    :remote-method="remoteMethodFormTypeId"
                    :loading="loadingFormTypeId"
                    @change="changeData($event,item,index)"
                  >
                    <el-option
                      v-for="item1 in formTypeIds"
                      :key="item1.id"
                      :label="item1.shortName"
                      :value="item1.id"
                    />
                  </el-select>
                </el-form-item>
                <div v-if="item.formTempId">
                  <AddTemplatePage
                    :ref="'templatePage_'+index"
                    :obj="dataForm"
                    :form-details-id="item.id"
                    :maintena-index="index"
                    :outlet-data="item"
                    @saveMaintena="saveMaintena"
                  />
                </div>
              </el-tab-pane>
              <!-- <div>
            <el-row type="flex" justify="center">
              <el-col :span="4" :offset="16">
                <el-button type="primary" size="mini" @click="handleAdd">添加</el-button>
              </el-col>
            </el-row>
            <br>
            <el-row
              v-for="(item,index) in dataForm.list"
              :key="item.key"
            >
              <el-form inline>
                <el-col :span="18">
                  <el-form-item label="类型" prop="formTempId">
                    <el-select
                      :ref="'select'+index"
                      v-model="item.formTempId"
                      class="w-150"
                      filterable
                      remote
                      clearable
                      reserve-keyword
                      placeholder="请输入"
                      :remote-method="remoteMethodFormTypeId"
                      :loading="loadingFormTypeId"
                      @change="changeData($event,item,index)"
                    >
                      <el-option
                        v-for="item1 in formTypeIds"
                        :key="item1.id"
                        :label="item1.shortName"
                        :value="item1.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-button v-if="item.isAdd === '1'" type="primary" @click="handleConf(item, index)">确定</el-button>
                  <el-button v-else type="primary" @click="handleUpdate(item, index)">修改</el-button>
                  <el-button type="primary" @click="handleDelete(item, index)">删除</el-button>
                </el-col>
              </el-form>
            </el-row>
          </div> -->
            </el-tabs>
          </div>
        </el-card>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :loading="saveSubmitLoading"
          class="sure-btn auto"
          @click="handleSave('2')"
        >保存并提交</el-button>
        <el-button type="primary" :loading="saveLoading" class="sure-btn" size="mini" @click="handleSave('1')">保存</el-button>
      </span>
    </el-dialog>

    <EditMaintenaFormDialog
      :dialog-visible="dialog.formEdit.visible"
      :obj="dialog.formEdit.obj"
      @closeDialog="closeFormEditDialog"
      @flushPage="flushFormEditPage"
    />
    <AddTemplateDialog
      :dialog-visible="templateDialogVisible"
      :obj="maintenaDetail"
      :form-details-id="formDetailsId"
      :maintena-index="maintenaIndex"
      :outlet-data="outletData"
      @saveMaintena="saveMaintena"
      @closeDialog="templateDialogVisible = false"
    />
  </div>
</template>

<script>
import {
  saveTMaintenanceDetailsDto,
  selectFormTempByCd,
  selectTMaintenanceDetailsDto,
  selectLastMaintenance2
} from '@/api/maintenanceManage'

import EditMaintenaFormDialog from '@/views/maintenanceManage/components/EditMaintenaFormDialog'
import AddTemplateDialog from './AddTemplateDialog'
import AddTemplatePage from './AddTemplatePage'
export default {
  name: 'EditMaintenanceDialog',
  components: {
    EditMaintenaFormDialog, AddTemplateDialog, AddTemplatePage
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    obj: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      editableTabsValue: '1',
      editableTabs: [],
      saveOrExit: '1', // 1退出 2 保存
      dialog: {
        formEdit: {
          visible: false,
          obj: {}
        }
      },
      templateDialogVisible: false,
      saveLoading: false,
      saveSubmitLoading: false,
      dataForm: {
        id: null,
        outletName: null,
        outletId: null,
        outletTypeName: null,
        outletType: null,
        equipmentId: null,
        equipmentTypeName: null,
        equipmentTypeId: null,
        enterpriseId: null,
        enterpriseName: null,
        list: [],
        opType: null,
        deleteIds: []// 用于记录删除的id
      },
      signPath: null,
      loadingFormTypeId: false,
      formTypeIds: [],
      maintenaDetail: {},
      formDetailsId: '',
      maintenaIndex: 0,
      // 判断使用哪个模板
      // outletData: {outlet: '',type: ''}
      outletData: null
    }
  },
  created() {

  },
  methods: {
    handleTabsEdit(targetName, action) {
      if (action === 'add') {
        // dataForm
        const tabsValue = (this.dataForm.list.length + 1) + ''
        this.dataForm.list.push({
          'maintenanceDetailsId': '',
          'id': '',
          'formTempId': '',
          'formTempIdName': '',
          'dataOp': '1',
          'isAdd': '1',
          'tabsValue': tabsValue
        })
        console.log(this.editableTabsValue)
        this.editableTabsValue = tabsValue
      }
      if (action === 'remove') {
        const tabs = this.dataForm.list
        let activeName = this.editableTabsValue
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.tabsValue === targetName) {
              const nextTab = tabs[index + 1] || tabs[index - 1]
              if (nextTab) {
                activeName = nextTab.tabsValue
              }
            }
          })
        }
        this.editableTabsValue = activeName
        this.dataForm.list = tabs.filter(tab => tab.tabsValue !== targetName)
      }
    },
    initData() {
      this.dataForm.deleteIds = []
      this.saveOrExit = '1'
      debugger
      selectTMaintenanceDetailsDto({ 'maintenanceId': this.obj.ids }).then(res => {
        this.dataForm = res.data.list
        this.dataForm.deleteIds = []
        this.remoteMethodFormTypeId()
        this.saveLoading = false
        this.saveSubmitLoading = false
        // outletData
        this.editableTabsValue = '1'
        console.log(this.editableTabsValue)
        // 初始化选中一项
        if (this.dataForm.list.length === 0) {
          this.handleTabsEdit(null, 'add')
        }
      }).catch(() => {
        this.saveLoading = false
        this.saveSubmitLoading = false
      })
    },
    // 查询类型选择框数据
    remoteMethodFormTypeId(query) {
      this.loadingFormTypeId = true
      const temp = {
        name: query,
        equipmentTypeId: this.dataForm.equipmentTypeId,
        enterpriseId: this.dataForm.enterpriseId
      }
      selectFormTempByCd(temp).then(data => {
        this.formTypeIds = data.data.list
        this.loadingFormTypeId = false
      })
    },
    changeData(event, item, index) {
      let data = {}
      debugger
      data = this.formTypeIds.find((item) => {
        return item.id === event
      })
      item.formTempIdName = data.shortName
      item.formTempId = data.id
      // 初始化
      console.log(index, item)
      selectLastMaintenance2({ 'outletId': this.dataForm.outletId, 'equipmentId': this.dataForm.equipmentId, 'formTempId': item.formTempId }).then(res2 => {
        console.log('上一次提交的表单记录', res2.data.list)
        this.dataForm.lastMaintenance = res2.data.list
        this.$set(this.dataForm.list, index, item)
      }).catch(() => {
      })
      // this.maintenaDetail = this.dataForm
      // this.formDetailsId = item.id
      // this.maintenaIndex = index
      // this.outletData = {
      //   formTempId: item.formTempId
      // }
    },
    // 返回运维表单数据
    saveMaintena(data) {
      console.log(data.maintenaIndex)
      this.dataForm.list[data.maintenaIndex].formContent = data.formContent
      this.dataForm.list[data.maintenaIndex].filePath = JSON.stringify(data.filePath)
      this.dataForm.list[data.maintenaIndex].videoPath = JSON.stringify(data.videoPath)
      this.dataForm.list[data.maintenaIndex].faultType = data.faultType
    },
    handleDelete(item, index) {
      this.$confirm('是否要删除？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (item.maintenanceDetailsId) {
          this.dataForm.deleteIds.push(item.maintenanceDetailsId)
        }
        this.dataForm.list.splice(index, 1)
      }).catch(() => {
        this.$message.info('已取消')
      })
    },
    handleUpdate(item, index) {
      this.templateDialogVisible = true
      this.maintenaDetail = this.dataForm
      this.formDetailsId = item.id
      this.maintenaIndex = index
      this.outletData = {
        formTempId: item.formTempId
      }
      // this.dialog.formEdit.visible = true
      // this.dialog.formEdit.obj.data = item
      // this.dialog.formEdit.obj.index = index
    },
    handleSave(flag) { // 2保存并提交  1 保存
      // 获取模板数据
      this.dataForm.list.map((item, i) => {
        if (this.$refs['templatePage_' + i]) {
          this.$refs['templatePage_' + i][0].handleSave()
        }
      })
      console.log(this.dataForm)
      if (!this.check()) return false
      if (flag === '2') {
        this.saveSubmitLoading = true
      } else {
        this.saveLoading = true
      }
      const data = []
      const list = []
      const formType = []
      const dateObj = { 'id': this.dataForm.id, 'opType': flag, 'list': list, formType: formType }
      data.push(dateObj)

      const adds = this.dataForm.list
      for (let i = 0; i < adds.length; i++) {
        const add = adds[i]
        formType.push(add.formTempIdName)
        if (add.dataOp === '1') { // 新增
          list.push({
            'formTempId': add.formTempId,
            'formContent': add.formContent,
            'recording': add.recording,
            'filePath': add.filePath,
            'videoPath': add.videoPath,
            'faultType': add.faultType,
            'dataOp': '1'
          })
        }
        if (add.maintenanceDetailsId !== null) { // 修改
          list.push({
            'maintenanceDetailsId': add.maintenanceDetailsId,
            'formContent': add.formContent,
            'recording': add.recording,
            'filePath': add.filePath,
            'videoPath': add.videoPath,
            'faultType': add.faultType,
            'formDetailsId': add.id,
            'dataOp': '2'
          })
        }
      }

      const deleteIds = this.dataForm.deleteIds
      for (let i = 0; i < deleteIds.length; i++) {
        list.push({ 'maintenanceDetailsId': deleteIds[i], 'dataOp': '-1' })
      }
      const p1 = new Promise((resolve, rej) => {
        // if (flag === '1') {
        //   this.$confirm('是否提交数据？', '提示', {
        //     confirmButtonText: '提交',
        //     cancelButtonText: '不提交',
        //     type: 'warning'
        //   }).then(() => {
        //     flag = '2'
        //     resolve(flag)
        //   }, () => {
        //     flag = '1'
        //     resolve(flag)
        //   }).catch(() => {

        //   })
        // } else {
        resolve(flag)
        // }
      })

      // then里面两个回调，默认第一个resolve,第二个reject；不会进入catch；如果只有一个回调则进入catch
      p1.then(re => {
        saveTMaintenanceDetailsDto(data).then(() => {
          if (re === '1') {
            this.$message.success('保存成功,数据未提交')
          } else {
            this.$message.success('保存并提交成功')
          }
          this.$emit('closeDialog')
          this.$emit('flushPage')
          if (flag === '2') {
            this.saveSubmitLoading = false
          } else {
            this.saveLoading = false
          }
          this.saveOrExit = '2'
        }).catch(() => {
          if (re === '2') {
            this.saveSubmitLoading = false
          } else {
            this.saveLoading = false
          }
        })
      }, err => {
        console.log('err::', err)
      }).catch(
        res => {
          console.log('catch data::', res)
        })
    },
    // 添加类型
    handleAdd() {
      this.dataForm.list.push({
        'maintenanceDetailsId': '',
        'id': '',
        'formTempId': '',
        'formTempIdName': '',
        'dataOp': '1',
        'isAdd': '1'
      })
    },
    handleConf(item, index) {
      if (!item.formTempId) {
        this.$message.warning('请选择类型')
      } else {
        if (this.check()) {
          console.log(item)
          item.isAdd = '2'
          this.templateDialogVisible = true
          this.maintenaDetail = this.dataForm
          this.formDetailsId = item.id
          this.maintenaIndex = index
          this.outletData = {
            formTempId: item.formTempId
          }
          // this.dialog.formEdit.visible = true
          // item.isAdd = '2'
          // this.dialog.formEdit.obj.data = item
          // this.dialog.formEdit.obj.index = index
        }
      }
    },
    check() {
      let obj
      const temp = []
      for (const itemElement of this.dataForm.list) {
        if (itemElement.formTempId) {
          if (temp.indexOf(itemElement.formTempId, 0) !== -1) {
            obj = itemElement
            break
          } else {
            temp.push(itemElement.formTempId)
          }
        }
      }
      if (obj != null) {
        this.$message.warning(obj.formTempIdName + '有重复的类型')
        return false
      } else {
        return true
      }
    },
    closeDialog() {
      if (this.saveOrExit === '1') {
        this.$confirm('数据未保存，是否退出?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$emit('closeDialog')
          this.$refs['form'].clearValidate()
        }, () => {

        }).catch(() => {

        })
      }
    },
    flushFormEditPage(arg) {
      const temps = this.dataForm.list[arg.index]
      temps.formContent = arg.formContent
      temps.recording = arg.recording
      temps.filePath = arg.filePath
      temps.videoPath = arg.videoPath
      temps.faultType = arg.faultType
      this.dialog.formEdit.visible = false
    },
    closeFormEditDialog() {
      this.dialog.formEdit.visible = false
    }

  }

}
</script>

<style lang="scss" scoped>

</style>
